<template>
  <el-dialog title="修改商品信息" v-model="bool" width="30%" center @close="closeDialog">
    <el-form ref="FORM" :model="form" label-width="80px" :rules="rules">

      <el-form-item label="商品名称" prop="title">
        <el-input v-model="form.title" />
      </el-form-item>

      <el-form-item label="商品价格" prop="price">
        <el-input type="text" v-model="form.price" />
      </el-form-item>

      <el-form-item label="商品图片" prop="coverImg">
        <el-upload class="avatar-uploader" :action="upload['action']" :file-list="upload['fileList']" :on-success="upload['handleSuccess']" :before-upload="upload['handleUpload']" :show-file-list="false" :name="upload['name']" multiple :limit="1">
          <img v-if="upload['imageUrl']" :src="upload['imageUrl']" class="avatar" />
          <i v-else class="el-icon-plus avatar-uploader-icon" />
        </el-upload>
      </el-form-item>

      <el-form-item label="商品详情" prop="goodsDetail">
        <QuillEditor theme="snow" ref="EDITOR" />
      </el-form-item>

    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button type="primary" @click="submit">确 定</el-button>
        <el-button @click="closeDialog">取 消</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script lang='js'>
import { onMounted, defineComponent, reactive, toRefs, ref, computed, getCurrentInstance } from "vue";
import { QuillEditor } from "@vueup/vue-quill";
import "@vueup/vue-quill/dist/vue-quill.snow.css";
import { ElMessage } from 'element-plus';
import { EDITGOODS } from '@/api';

function useEdit(Dialog, FORM, EDITOR, emit) {
  const submit = () => {
    Dialog.form.goodsDetail = EDITOR.value.getText().replace(/(\r\n|\n|\r)/gm, '<br />') !== '<br />' ?
    EDITOR.value.getHTML() : '';
    FORM.value.validate(async valid => {
      if (!valid) return ElMessage.error('验证未通过');
      
      const params = {
        goodsId: Dialog.goodsId,
        title: Dialog.form.title,
        price: Dialog.form.price,
        thumbnail: Dialog.form.coverImg,
        goodsDetail: Dialog.form.goodsDetail
      };
      // const result = await ajax({url: 'goods/edit', params, method: 'post'});
      const result = await EDITGOODS(params);
      FORM.value.resetFields();
      EDITOR.value.setText("");
      emit('response');
      emit('update:modelValue', false);
    });

  };

  return  { submit }
}

async function useLoadEdit(Dialog, EDITOR) {
  const data = await ajax({url: 'goods/get', params: { goodsId: Dialog.goodsId }});
  Dialog.form = Object.assign(data, { coverImg: data.thumbnail });
  Dialog.upload.imageUrl = import.meta.env.VITE_APP_URL + data.thumbnail;
  EDITOR.value.setHTML(data.goodsDetail);
}
export default defineComponent({
  name: "~Product",
  components: { QuillEditor, },
  props: {
    modelValue: Boolean,
    pid: Number,
  },
  emits: ['update:modelValue', "response"], 
  setup(props, { emit, slots, attr }) {
    const FORM = ref();
    const EDITOR = ref();
    const bool = computed(() => props.modelValue);
    const Dialog = reactive({
      goodsId: props.pid,
      form: {
        title: '',
        price: '',
        coverImg: '',
        goodsDetail: ''
      },
      rules: {
        title: [{ required: true, trigger: 'blur', message: '请输入商品名称' }],
        price: [{ required: true, trigger: 'blur', message: '请输入商品价格' }],
        coverImg: [{ required: true, message: "请上传商品主图", trigger: "blur" }],
        goodsDetail: [{ required: true, message: "请输入商品详情", trigger: "blur" }],
      },
      upload: {
        action: import.meta.env.VITE_APP_URL + '/goods/fileUpload',
        fileList: [],
        imageUrl: '',
        name: "image",
        handlePreview() {

        },
        handleSuccess(response) {
          Dialog.upload.imageUrl = import.meta.env.VITE_APP_URL + response.msg;
          Dialog.form.coverImg = response.msg;
        },
        handleRemove() {

        },
        handleUpload(file) { // beforeUpload
          const arr = file.name.split('.')[1];
          const bool = ['jpg', 'jpeg', 'png'].includes(arr);
          if (!bool) return ElMessage.error('请上传jpg, jpeg, png类型图片文件！');
        }
      },
      closeDialog() {
        Dialog.upload.imageUrl = '';
        emit('update:modelValue', !bool);
      }
    });
    onMounted(useLoadEdit.call(null, Dialog, EDITOR));
    
    return {
      FORM,
      EDITOR,
      bool,
      ...toRefs(Dialog),
      ...useEdit(Dialog, FORM, EDITOR, emit)
    };
  }
});
</script>

<style lang='css' scoped>
:deep(.avatar-uploader .el-upload) {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 80px;
  height: 80px;
}
</style>
